<template>
  <ContentWrap>
    <Search
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      @register="searchRegister"
    />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton @click="importSql">导入SQL</BaseButton>
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      @refresh="refresh"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" :fullscreen="true" @close="restForm">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </ElDialog>
  <el-dialog v-model="centerDialogVisible" title="导入SQL" center>
    <div style="border: 1px solid #dcdfe6">
      <code-editor :userWorker="false" :readonly="false" v-model="sqlCode" ref="ecEditor" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="importSqlSave"> 导入 </el-button>
      </div>
    </template>
  </el-dialog>
  <Dialog v-model="codeDownloadDialogVisble" title="代码下载" maxHeight="50px" maxWidth="30%">
    <Form @register="codeDownloadFormRegister" :schema="codeDownloadFormSchema" />
    <template #footer>
      <BaseButton type="primary" :loading="downLoading" @click="downCode"> 下载 </BaseButton>
      <BaseButton @click="codeDownloadDialogVisble = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { reactive, ref, unref, h } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { Table, TableColumn } from '@/components/Table'
import {
  getGeneratePageListApi,
  deleteGenerate,
  syncDataBase,
  codeFileGenerator,
  importSqlApi
} from '@/api/generate'
import { useSearch } from '@/hooks/web/useSearch'
import CodeEditor from '@/components/variant-form3/code-editor/index.vue'
import {
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElDialog,
  ElMessage,
  ElTag
} from 'element-plus'
import { Form, FormSchema } from '@/components/Form'
import { BaseButton } from '@/components/Button'
import Write from './components/Write.vue'
import { useForm } from '@/hooks/web/useForm'
const { t } = useI18n()
const sqlCode = ref('')
const downLoading = ref(false)
const centerDialogVisible = ref(false)
const codeDownloadDialogVisble = ref(false)
const { searchRegister, searchMethods } = useSearch()
const { getFormData } = searchMethods
const modelId = ref('')
const codeDownloadFormSchema = ref<FormSchema[]>([
  {
    field: 'moduleName',
    label: '模块名称',
    component: 'Input',
    componentProps: {
      placeholder: 'jeehentor-xxx'
    }
  },
  {
    field: 'packagePath',
    label: '包路径',
    component: 'Input',
    componentProps: {
      placeholder: 'com.jeehentor.test'
    }
  }
])
const { formRegister: codeDownloadFormRegister, formMethods } = useForm()
const { setValues, getFormData: dowmCodeFormData, getElFormExpose } = formMethods
const importSql = () => {
  centerDialogVisible.value = true
}
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const formData = await getFormData()
    const res = await getGeneratePageListApi({
      tableName: formData.tableName,
      page: { size: unref(pageSize), current: unref(currentPage) }
    })
    return {
      list: res.result.records || [],
      total: res.result.total
    }
  },
  fetchDelApi: async () => {
    const res = await deleteGenerate(unref(modelId))
    return !!res
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList, refresh, delList, getElTableExpose } = tableMethods
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'tableName',
    label: t('model.tableName'),
    component: 'Input'
  }
])
const importSqlSave = async () => {
  const res = await importSqlApi({ sql: sqlCode.value })
  if (res.success) {
    centerDialogVisible.value = false
    ElMessage.success('导入成功')
    refresh()
  } else {
    ElMessage.error(res.message)
  }
  console.log('sql', sqlCode.value)
}
const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'tableName',
    label: t('model.tableName')
  },
  {
    field: 'tableComment',
    label: t('model.tableComment')
  },
  {
    field: 'versionCode',
    label: t('model.versionCode')
  },
  {
    field: 'syncStatus',
    label: t('model.syncStatus'),
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row.syncStatus === '1' ? (
              <ElTag type="success">已同步</ElTag>
            ) : (
              <ElTag type="warning">未同步</ElTag>
            )}
          </>
        )
      }
    }
  },
  {
    field: 'createByLabel',
    label: t('model.createBy')
  },
  {
    field: 'createTime',
    label: t('model.createTime')
  },
  {
    field: 'updateByLabel',
    label: t('model.updateBy')
  },
  {
    field: 'updateTime',
    label: t('model.updateTime')
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <ElDropdown style="margin-left: 15px;">
              {{
                default: () => {
                  return (
                    <>
                      <BaseButton type="success" loading={syncLoading.value}>
                        更多
                      </BaseButton>
                    </>
                  )
                },
                dropdown: () => {
                  return (
                    <ElDropdownMenu>
                      {{
                        default: () => {
                          return (
                            <>
                              <ElDropdownItem onClick={() => syncDb(row.id)}>
                                同步模型
                              </ElDropdownItem>
                              <ElDropdownItem onClick={() => codeDownloadDialog(row)}>
                                下载代码
                              </ElDropdownItem>
                            </>
                          )
                        }
                      }}
                    </ElDropdownMenu>
                  )
                }
              }}
            </ElDropdown>
            <BaseButton style="margin-left: 15px;" type="danger" onClick={() => delData(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()
const syncLoading = ref(false)
const saveLoading = ref(false)
const restForm = () => {
  const write = unref(writeRef)
  write.resetForm()
}
const downCode = async () => {
  const formData = await dowmCodeFormData()
  await codeFileGenerator(
    {
      mainId: downModel.value.id,
      packagePath: formData.packagePath,
      moduleName: formData.moduleName
    },
    downModel.value.tableName
  )
  codeDownloadDialogVisble.value = false
}
const action = (row: any, type: string) => {
  const write = unref(writeRef)
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
  write?.setFormValue(row)
}
const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}
const syncDb = async (id) => {
  syncLoading.value = true
  try {
    const res = await syncDataBase(id)
    if (res.success) {
      ElMessage.success(res.message)
    }
  } catch (e: any) {
    console.log(e)
  } finally {
    setTimeout(() => {
      syncLoading.value = false
      refresh()
    }, 1000)
  }
}
const save = async () => {
  const write = unref(writeRef)
  const formData = actionType.value === 'edit' ? await write?.updateData() : await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    dialogVisible.value = false
    refresh()
  }
}
const downModel = ref()
const codeDownloadDialog = (row) => {
  downModel.value = row
  codeDownloadDialogVisble.value = true
}
const delLoading = ref(false)
const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  modelId.value = row.id || ''
  console.log('menuId.value', row)
  delLoading.value = true
  await delList(1).finally(() => {
    delLoading.value = false
  })
}
</script>
<style scoped>
.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}

.example-showcase .el-dropdown-link {
  display: flex;
  color: var(--el-color-primary);
  cursor: pointer;
  align-items: center;
}
</style>
